<?php
/*********************************************
  CPG Dragonfly™ CMS
  ********************************************
  Copyright © 2004 - 2005 by CPG-Nuke Dev Team
  http://www.dragonflycms.com

  Dragonfly is released under the terms and conditions
  of the GNU GPL version 2 or any later version
**********************************************/

class Dragonfly_Module_Statistics
{

	public static
		$misc,
		$metered;

	private static
		$db,
		$CFG,
		$TPL;

	public static function run()
	{
		self::$db = Dragonfly::getKernel()->SQL;
		self::$TPL = Dragonfly::getKernel()->OUT;
		self::$TPL->sitename = Dragonfly::getKernel()->CFG->global->sitename;
		self::$TPL->startdate = Dragonfly::getKernel()->CFG->global->startdate;
		self::$TPL->metered = array();
		self::$TPL->misc = array();
		list(self::$TPL->total) = self::$db->uFetchRow('SELECT SUM(count) FROM '.self::$db->TBL->counter.' WHERE type IN ("browser","bot")');
		self::$TPL->total++;

		Dragonfly_Page::setTitle('. '. _StatisticsLANG);

		$year = $_GET->int('year');
		$month = $_GET->int('month');
		$date = $_GET->int('date');

		if ($year) {
			self::$TPL->stats = true;
			Dragonfly_Output_Css::add('statistics');
			require_once('header.php');
			self::$TPL->display('Statistics/stats');
			if ($month) {
				if ($date) {
					self::showHourlyStats($year, $month, $date);
				} else {
					self::showYearStats($year);
					self::showMonthStats($year, $month);
					self::showDailyStats($year, $month, $date);
				}
			} else {
				self::showYearStats($year);
				self::showMonthStats($year, $month);
			}
			self::$TPL->display('Statistics/metered');
		} else if (isset($_GET['details'])) {
			self::details();
		} else {
			self::statsMain();
		}
	}

	protected static function details()
	{

		self::$TPL->details = true;

		$L10N = Dragonfly::getKernel()->L10N;
		self::$TPL->today = $L10N->date('F d, Y', time());

		Dragonfly_Output_Css::add('statistics');
		require_once('header.php');

		self::$TPL->topMonth = self::$db->uFetchRow("
			SELECT year, month, SUM(hits) FROM ".self::$db->TBL->stats_hour."
			GROUP BY month, year
			ORDER BY hits DESC",SQL_NUM);
		self::$TPL->topMonth = self::getmonth(self::$TPL->topMonth[1]).' '.self::$TPL->topMonth[0].' ('.self::$TPL->topMonth[2].' '._HITS.')';

		self::$TPL->topDay = self::$db->uFetchRow("SELECT year, month, date, SUM(hits) FROM ".self::$db->TBL->stats_hour."
			GROUP BY date, month, year
			ORDER BY hits DESC",SQL_NUM);
		self::$TPL->topDay = self::$TPL->topDay[2].' '.self::getmonth(self::$TPL->topDay[1]).' '.self::$TPL->topDay[0].' ('.self::$TPL->topDay[3].' '._HITS.')';

		self::$TPL->topHour = self::$db->uFetchRow("SELECT year, month, date, hour, hits from ".self::$db->TBL->stats_hour." ORDER BY hits DESC",SQL_NUM);
		self::$TPL->topHour[3] = str_pad(self::$TPL->topHour[3], 2, '0', STR_PAD_LEFT);
		self::$TPL->topHour[3] = self::$TPL->topHour[3].':00 - '.self::$TPL->topHour[3].':59';
		self::$TPL->topHour = self::$TPL->topHour[3].' '._ON.' '.self::getmonth(self::$TPL->topHour[1]).' '.self::$TPL->topHour[2].', '.self::$TPL->topHour[0].' ('.self::$TPL->topHour[4].' '._HITS.')';

		$now = explode('-',  $L10N->date('d-m-Y', time()));
		self::showYearStats($now[2]);
		self::showMonthStats($now[2], $now[1]);
		self::showDailyStats($now[2], $now[1], $now[0]);
		self::showHourlyStats($now[2], $now[1], $now[0]);

		self::$TPL->display('Statistics/stats');
		self::$TPL->display('Statistics/metered');
	}

	protected static function statsMain()
	{
		self::$TPL->main = true;

		Dragonfly_Output_Css::add('Statistics/statistics');
		require_once('header.php');

		# Built-in metered stats
		self::$TPL->metered = array(
			'bot' => array(
				'title' => _SEARCH_ENGINES,
				'total_hits' => 0,
				'vars_hits' => array(),
				'rows' => array()
			),
			'browser' => array(
				'title' => _BROWSERS,
				'total_hits' => 0,
				'vars_hits' => array(),
				'rows' => array()
			),
			'os' => array(
				'title' => _OPERATINGSYS,
				'total_hits' => 0,
				'vars_hits' => array(),
				'rows' => array()
			)
		);

		$result  = self::$db->sql_query('SELECT type, var, count FROM '.self::$db->TBL->counter.' WHERE count>0 ORDER BY count DESC, var');
		while (list($type, $var, $count) = self::$db->sql_fetchrow($result)) {
			if ($type === 'os' && $var == 'OS/2') { $var = 'OS2'; }
			self::$TPL->metered[$type]['total_hits'] += $count;
			self::$TPL->metered[$type]['vars_hits'][$var] = $count;
		}
		$result->free();

		foreach (self::$TPL->metered as $type => $array) {
			foreach ($array['vars_hits'] as $var => $count) {
				self::$TPL->metered[$type]['rows'][] = array(
					'class' => strtolower($var),
					'name' => $var,
					'hits' => $count
				);
				unset(self::$TPL->metered[$type]['vars_hits']);
			}
		}

		# Built-in miscellaneous Stats
		$count = self::$db->TBL->users->count('user_level > 0') - 1;
		self::$TPL->misc[] = array('class' => 'users', 'name' => _REGUSERS, 'hits' => $count);

		# Plugins
		self::$metered = self::$misc = array();
		$plugins = Dragonfly_Modules::ls('plugins/statistics.inc');
		foreach ($plugins as $file) include_once($file);
		self::$TPL->metered = array_merge(self::$TPL->metered, self::$metered);
		self::$TPL->misc = array_merge(self::$TPL->misc, self::$misc);

		self::$TPL->display('Statistics/stats');
		self::$TPL->display('Statistics/metered');
		self::$TPL->display('Statistics/misc');
	}

	protected static function showYearStats($nowyear)
	{
		list($total) = self::$db->uFetchRow('SELECT SUM(hits) FROM '.self::$db->TBL->stats_hour);
		self::$TPL->metered['yearly'] = array(
			'title' => _YEARLYSTATS,
			'total_hits' => $total,
			'rows' => array()
		);

		$result = self::$db->query('SELECT year, SUM(hits) FROM '.self::$db->TBL->stats_hour.' GROUP BY year ORDER BY year');
		while (list($year,$hits) = $result->fetch_row()){
			self::$TPL->metered['yearly']['rows'][] = array(
				'name' => $year,
				'url' => $year != $nowyear && $hits ? "&amp;year=$year" : '',
				'hits' => $hits
			);
		}
		$result->free();
	}

	protected static function showMonthStats($nowyear, $nowmonth)
	{
		$total = 0;
		//$data = array_fill_keys(range(1,12), 0);

		$result = self::$db->query('SELECT month, SUM(hits) as hits FROM '.self::$db->TBL->stats_hour." WHERE year='$nowyear' GROUP BY month ORDER BY month");
		while ($row = $result->fetch_assoc()) {
			$total += $row['hits'];
			$data[$row['month']] = $row['hits'];
		}

		self::$TPL->metered['monthly'] = array(
			'title' => _MONTLYSTATS.' '.$nowyear,
			'total_hits' => $total,
			'rows' => array()
		);

		foreach ($data as $month => $hits) {
			self::$TPL->metered['monthly']['rows'][] = array(
				'name' => self::getmonth($month),
				'url' => $month != $nowmonth && $hits ? "&amp;year=$nowyear&amp;month=$month" : '',
				'hits' => $hits
			);
		}
		$result->free();
	}

	protected static function showDailyStats($year, $month, $nowdate=0)
	{
		$total = 0;
		$data = array();

		$result = self::$db->query('SELECT date, SUM(hits) as hits FROM '.self::$db->TBL->stats_hour." WHERE year='$year' AND month='$month' GROUP BY date ORDER BY date");
		while ($row = $result->fetch_assoc()) {
			$total += $row['hits'];
			$data[$row['date']] = $row['hits'];
		}
		self::$TPL->metered['daily'] = array(
			'title' => _DAILYSTATS.' '.self::getmonth(intval($month)),
			'total_hits' => $total,
			'rows' => array()
		);

		foreach ($data as $date => $hits) {
			self::$TPL->metered['daily']['rows'][] = array(
				'name' => $date,
				'url' => $date != $nowdate && $hits  ? "&amp;year=$year&amp;month=$month&amp;date=$date" : '',
				'PERC' => round(100 * $hits/$total,0),
				'hits' => $hits
			);
		}
	}

	protected static function showHourlyStats($year, $month, $date)
	{
		$total = 0;
		$data = array();
		$hours = array_fill_keys(range(0,23), 0);

		$result = self::$db->query('SELECT hour, hits FROM '.self::$db->TBL->stats_hour." WHERE year=$year AND month=$month AND date=$date GROUP BY hour, hits ORDER BY hour");
		while ($row = $result->fetch_assoc()) {
				$total += $row['hits'];
				$hours[$row['hour']] = $row['hits'];
		}
		self::$TPL->metered['hourly'] = array(
			'title' => _HOURLYSTATS.' '.self::getmonth($month).' '.$date.', '.$year,
			'total_hits' => $total,
			'rows' => array()
		);

		foreach ($hours as $hour => $hits) {
			$hour = str_pad($hour, 2, '0', STR_PAD_LEFT);
			self::$TPL->metered['hourly']['rows'][] = array(
				'name' => "$hour:00 - $hour:59",
				'PERC' => round(100 * $hits/$total,0),
				'hits' => $hits
			);
		}
	}

	protected static function getmonth($k)
	{
		static $months;
		if (empty($months)) {
			$months = Dragonfly::getKernel()->L10N->get('_time','F');
		}
		return isset($months[$k]) ? $months[$k] : '';
	}
}
if ('GET' === $_SERVER['REQUEST_METHOD']) Dragonfly_Module_Statistics::run();
